# coding:utf8
"""用class重构Send Mail
"""

import smtplib
from email.mime.text import MIMEText
from email.header import Header


class SendMail:
    """发送邮件
    1. set_recv_er
    2. set_massage
    3. send_mail() <- ok
    创建消息实例，创建SMTP实例，
        1.消息实例：
            返回消息对象
    """

    def __init__(self, smtp_host, user, passwd, *args, **kwargs):
        self.smtp_host = smtp_host
        self.user = user
        self.passwd = passwd
        self.usr_p = (user, passwd)
        self.args = args
        self.kwargs = kwargs
        self.recv_s = []

        for _re in ['receive', 'receiver', 'recv']:
            if _re in kwargs: self.recv_s.extend([kwargs[_re]])

        if 'subject' in kwargs:
            self.subject = kwargs['subject']
        else:
            self.subject = None

        if 'msg' in kwargs:
            self.msg = kwargs['mag']
        else:
            self.msg = None

        self.SMTPServer = smtplib.SMTP
        self.Massages = []

    def create_massage(self):
        """创建一个消息对象"""
        if not len(self.recv_s): self.recv_s = input("请输入收件人(多个用','隔开)：").split(',')
        if not self.subject: self.subject = input("请输入邮件的标题：")
        if not self.msg: self.msg = input("请输入邮件的内容：")

        for recv in self.recv_s:
            massage = MIMEText(self.msg, _charset='utf8')
            massage['Subject'] = Header(self.subject, 'utf8')
            massage['From'] = Header(self.user, 'utf8')
            massage['To'] = Header(recv, 'utf8')
            _ms = (recv, massage.as_string())
            self.Massages.append(_ms)

    def set_recv(self, recv):
        """ :param recv: 可以是字符串或者一个可迭代的对象（列表，元组）"""
        if isinstance(recv, str):
            self.recv_s = [recv]
        else:
            self.recv_s = recv

    def set_massage(self, subject, msg):
        """设置字符串对象的subject 和 msg.
        :param subject: 邮件对象的 标题
        :param msg: 邮件对象的正文
        """
        self.subject = subject
        self.msg = msg

    def send_mail(self):
        """ 发送邮件 """
        self.SMTPServer = smtplib.SMTP(self.smtp_host)
        self.SMTPServer.connect(self.smtp_host)
        # print(self.usr_p)
        self.SMTPServer.login(*self.usr_p)
        self.create_massage()
        for _msg in self.Massages:
            self.SMTPServer.sendmail(self.user, self.recv_s[0], _msg[1])

    def send_one_mail(self, receive, subject, msg):
        if isinstance(receive, str): self.recv_s = [receive]
        else: self.recv_s = receive
        self.subject = subject
        self.msg = msg
        self.create_massage()
        self.send_mail()


class SendMailAuto(SendMail):
    """
    实现实例化进发送
    """
    def __init__(self, receives, subject, massage,
                 smtp_host, user, passwd, *args, **kwargs):
        # super().__init__(smtp_host, user, passwd, *args, **kwargs)
        self.smtp_host = smtp_host
        self.user = user
        self.passwd = passwd
        self.usr_p = (user, passwd)

        self.SMTPServer = smtplib.SMTP  # 初始化SMTP服务器
        self.Massages = []

        self.send_one_mail(receives, subject, massage)


class SendMailFrom149(SendMailAuto):
    """ 从指定的1491311784@qq.com发送邮件"""
    SMTP_HOST = 'smtp.qq.com'
    SENDER = '1491311784@qq.com'
    _PASSWD = 'fxvvlznnwkclheic'

    def __init__(self, receives, subject, massage, *args, **kwargs):
        super().__init__(receives, subject, massage,
                         smtp_host=self.SMTP_HOST,
                         user=self.SENDER,
                         passwd=self._PASSWD,
                         *args, **kwargs)


class MassOneMail(SendMail):
    """
    把同一封邮件同时发送给列表中的所有人；
    """
    def __init__(self, smtp_host, user, passwd, *args, **kwargs):
        super().__init__(smtp_host, user, passwd, *args, **kwargs)


if __name__ == '__main__':
    dic_sender = {'pop_host': 'pop.qq.com',
                  'smtp_host': 'smtp.qq.com',
                  'user': '1491311784@qq.com',
                  'passwd': 'fxvvlznnwkclheic',
                  }
    s = SendMailAuto('lee_cq@icloud.com', 'test_sub', 'test_mag', **dic_sender)
    #s.set_recv('  670343981@qq.com')
    # s.set_massage('class_test_subject', 'Class_test_content')
    #s.send_mail()
